package org.finesys.system.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.finesys.common.core.constants.RestApiConfig;
import org.finesys.common.core.module.R;
import org.finesys.common.security.core.annotation.Inner;
import org.finesys.system.api.entity.SysFile;
import org.finesys.system.constants.ControllerRestApiConfig;
import org.finesys.system.service.SysFileService;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.hutool.core.io.IoUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;

@RestController
@RequiredArgsConstructor
@RequestMapping(ControllerRestApiConfig.FILE)
@Tag(name = "文件管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class SysFileController {

    private final SysFileService sysFileService;

    @Operation(summary = "分页查询")
    @GetMapping(RestApiConfig.PAGE)
    public R<IPage<SysFile>> getPage(Page<SysFile> page, SysFile sysFile) {
        return R.success(sysFileService.findPage(page, sysFile));
    }

    @Operation(summary = "上传")
    @PostMapping(value = RestApiConfig.UPLOAD)
    public R<?> upload(@RequestParam("file") MultipartFile multipartFile) {
        return sysFileService.uploadFile(multipartFile);
    }
    @Operation(summary = "上传")
    @PostMapping(value = RestApiConfig.UPLOADS)
    public R<?> upload(@RequestParam("file") MultipartFile[] multipartFiles) {
        if(multipartFiles!=null&&multipartFiles.length>0){
            List<R<?>> resultList=new ArrayList<>();
            for(MultipartFile multipartFile:multipartFiles){
                R<?> result=sysFileService.uploadFile(multipartFile);
                resultList.add(result); 
            }
            return R.success(resultList);
        }
        return R.failed("上传失败");
    }
    @Operation(summary = "下载")
    @PostMapping(value = RestApiConfig.DOWNLOAD)
    public void download(@RequestBody SysFile sysFile, HttpServletResponse response) {
        sysFileService.getFile(sysFile.getBucketName(), sysFile.getFileName(), response);
    }

    @Operation(summary = "下载")
    @GetMapping(value = RestApiConfig.DOWNLOAD + "/{bucketName}/{fileName}")
    public void download(@PathVariable String bucketName, @PathVariable String fileName, HttpServletResponse response) {
        sysFileService.getFile(bucketName, fileName, response);
    }

    @Operation(summary = "删除")
    @DeleteMapping(value = RestApiConfig.DELETE)
     @PreAuthorize("@pms.hasPermission('sys_file_del')")
    public R<?> delete(@RequestBody Long[] ids, HttpServletResponse response) {
        for (Long id : ids) {
            sysFileService.deleteFile(id);
        }
        return R.success();
    }

    /**
     * 获取文件
     *
     * @param bucket   桶名称
     * @param fileName 文件空间/名称
     * @param response
     * @return
     */
    @Inner(false)
    @GetMapping("/{bucket}/{fileName}")
    public void file(@PathVariable String bucket, @PathVariable String fileName, HttpServletResponse response) {
        sysFileService.getFile(bucket, fileName, response);
    }

    /**
     * 获取本地（resources）文件
     *
     * @param fileName 文件名称
     * @param response 本地文件
     */
    @SneakyThrows
    @GetMapping("/local/file/{fileName}")
    public void localFile(@PathVariable String fileName, HttpServletResponse response) {
        ClassPathResource resource = new ClassPathResource("file/" + fileName);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IoUtil.copy(resource.getInputStream(), response.getOutputStream());
    }
}
